<?php

namespace app\common\model;

use think\Model;
use think\Validate;

class Admin extends Model
{
    const USER_TYPE = [
       'admin' => 0, //管理员
        'fdy' => 1, //辅导员
        'yc' => 2,  //院长
        'sg' => 3,  // 宿管
    ];

    /**
     * 保存
     * @param array $data
     */
    public function saveData($data)
    {
        $validate = Validate::make([
            'user_name' => 'require',
        ], [
            'user_name' => '用户名必须',
        ]);
        if (!$validate->check($data)) {
            exception($validate->getError());
        }
        if (!empty($data['user_password'])) {
            $data['user_password'] = encryptAdminPassword($data['user_password']);
        } else {
            unset($data['user_password']);
        }

        if (!empty($data['uid'])) {
            return $this->edit($data);
        } else {
            return $this->add($data);
        }
    }

    /**
     * 登录验证密码
     * @param  [type] $username [description]
     * @param  [type] $password [description]
     * @return [type]           [description]
     */
    public function checkPassword($username, $password, $user_type = 0)
    {
        $where['user_name']     = $username;
        $where['user_password'] = encryptAdminPassword($password);
        return $this->where($where)->where('user_type','in',$user_type)->find();
    }

    /**
     * 获取登录用户信息
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public function getUserInfo($uid)
    {
        $data         = $this->where('uid', $uid)->find();
        $data['auth'] = model('AdminRole')->getAuth($data['role_id']);
        return $data;
    }

    public function add($data)
    {
        $validate = Validate::make([
            'user_password' => 'require',
        ], [
            'user_password' => '密码必须',
        ]);
        if (!$validate->check($data)) {
            exception($validate->getError());
        }
        return $this->insert($data);
    }

    public function edit($data)
    {
        $data['reg_time'] = time();
        $data['reg_ip']   = request()->ip();
        return $this->where('uid', $data['uid'])->update($data);
    }

    public function delData($uid)
    {
        return $this->where([['uid', '=', $uid], ['is_super', '=', 0]])->delete();
    }

    /**
     * 自动登录用户
     *
     * @param integer $uid
     */
    public function login($uid)
    {
        // 更新登录信息
        $data = array(
            'last_login_time' => time(),
            'last_login_ip'   => request()->ip(),
        );
        return $this->where('uid', $uid)->inc('login_count')->update($data);
    }
}
